package livesun.justiceeternal.activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import livesun.justiceeternal.R;
import livesun.justiceeternal.base.BaseActivity;
import livesun.justiceeternal.view.ListViewForScrollView;
import livesun.justiceeternal.view.TagAdapter;
import livesun.justiceeternal.view.TagLayout;
import livesun.justiceeternal.view.titlebar.TranslucentUtils;

/**
 * 类描述：搜索页面
 * 创建人：livesun
 * 创建时间：2018/1/3.
 * 修改人：
 * 修改时间：
 * github：https://github.com/livesun
 */
public class SearchActivity extends BaseActivity {

    private TagLayout mHot;
    private ListViewForScrollView mListView;
    private TextView mTv_clear;
    private EditText mEt_search;
    private ImageView mClearIv;
    private ImageView mSearchImg;
    private Intent mIntent;

    @Override
    public int getResourcesId() {
        isTranslucentUtils(Color.parseColor("#E9EAEA"),true);
        return R.layout.activity_search;
    }

    @Override
    public void initView() {
        mIntent = new Intent(this,GetScoreActivity.class);
        //热搜
        mHot = findView(R.id.flowlayout_hot);
        //搜索历史
        mListView = findView(R.id.listView);
        //清除搜索历史
        mTv_clear = findView(R.id.tv_clear);

        //返回按钮
        ImageView back=findView(R.id.search_back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        //输入框
        mEt_search = findView(R.id.search_edit);
        //清空输入框
        mClearIv = findView(R.id.search_text_clear);
        //搜索按钮
        mSearchImg = findView(R.id.search_img);

        //初始化热搜
        initHot();
        //搜索框
        initEdit();
        // 第一次进入查询所有的历史记录
        queryData("");
    }

    private void initEdit() {
        // 搜索框的键盘搜索键点击回调
        mEt_search.setOnKeyListener(new View.OnKeyListener() {// 输入完后按键盘上的搜索键

            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == android.view.KeyEvent.KEYCODE_ENTER && event.getAction() == android.view.KeyEvent.ACTION_DOWN) {// 修改回车键功能
                    search();
                }
                return false;
            }
        });

        // 搜索框的文本变化实时监听
        mEt_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().trim().length() == 0) {
                    mClearIv.setVisibility(View.INVISIBLE);
                } else {
                    mClearIv.setVisibility(View.VISIBLE);
                }
                String tempName = mEt_search.getText().toString();
                // 根据tempName去模糊查询数据库中有没有数据
                if(TextUtils.isEmpty(tempName)){
                    queryData("");
                }else{
                    queryData(tempName);
                }


            }
        });
    }

    private void search() {
        // 先隐藏键盘
        ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
                getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        // 按完搜索键后将当前查询的关键字保存起来,如果该关键字已经存在就不执行保存
        boolean hasData = hasData(mEt_search.getText().toString().trim());
        if (!hasData) {
            if(!TextUtils.isEmpty(mEt_search.getText().toString().trim())){
                insertData(mEt_search.getText().toString().trim());
            }
        }
        // TODO 根据输入的内容模糊查询商品，并跳转到另一个界面，由你自己去实现
        String keyName = mEt_search.getText().toString().trim();
        if(!TextUtils.isEmpty(keyName)){
            action(keyName);
            mEt_search.setText(keyName);
        }

        queryData("");
    }


    private void initHot() {


        List<TagBean> datas=new ArrayList<>();
        datas.add(new TagBean(Color.parseColor("#F8F2EC"),"我们仍未知道那天所看见的花的名字"));
        datas.add(new TagBean(Color.parseColor("#F8F2EC"),"Fly Me to the Moon"));
        datas.add(new TagBean(Color.parseColor("#F8EAEB"),"一番の宝物"));
        datas.add(new TagBean(Color.parseColor("#F2F2F2"),"空之轨迹"));
        datas.add(new TagBean(Color.parseColor("#F2F5E9"),"某科学的超电磁炮"));
        datas.add(new TagBean(Color.parseColor("#F2F5E9"),"打上花火"));
        datas.add(new TagBean(Color.parseColor("#F2F5E9"),"妖精的尾巴"));
        datas.add(new TagBean(Color.parseColor("#F8EAEB"),"四月是你的谎言"));
        datas.add(new TagBean(Color.parseColor("#E8F6F6"),"千与千寻"));
        datas.add(new TagBean(Color.parseColor("#F8F2EC"),"缘之空"));
        datas.add(new TagBean(Color.parseColor("#E8F6F6"),"极乐净土"));
        datas.add(new TagBean(Color.parseColor("#F2F2F2"),"White Album"));
        mHot.setAdapter(new MyAdapter(datas));
    }

    private void action(String name) {

        mIntent.putExtra("keyword",name);
        startActivity(mIntent);
    }

    @Override
    public void initListener() {
        //一键清除
        mClearIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!TextUtils.isEmpty(mEt_search.getText().toString().trim())) {
                    mEt_search.setText("");
                }
            }
        });
        //清楚历史记录
        mTv_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deleteData();
                queryData("");
            }
        });

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView parent, View view, int position, long id) {
                TextView textView = (TextView) view.findViewById(android.R.id.text1);
                String name = textView.getText().toString();
                //点击后直接跳转
                action(name);
                mEt_search.setText(name);//点击把值装配到搜索栏中
                //也可以在此跳转页面，看需求。

            }

        });
        mSearchImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                search();
            }
        });
    }

    @Override
    public void onClick(View v, int id) {

    }

    @Override
    protected boolean isShowTitle() {
        return false;
    }



//============================数据库相关(begin)====================================
private RecordSQLiteOpenHelper helper = new RecordSQLiteOpenHelper(this);
    private SQLiteDatabase db;
    /**
     * 插入数据
     */
    private void insertData(String tempName) {
        db = helper.getWritableDatabase();
        db.execSQL("insert into records(name) values('" + tempName + "')");
        db.close();
    }

    /**
     * 模糊查询数据
     */
    private void queryData(String tempName) {
        try {
            Cursor cursor = helper.getReadableDatabase().rawQuery(
                    "select id as _id,name from records where name like '%" + tempName + "%' order by id desc ", null);
            // 创建adapter适配器对象
            BaseAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, new String[]{"name"},
                    new int[]{android.R.id.text1}, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
            // 设置适配器
            mListView.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        }catch (Exception e){

        }
    }

    /**
     * 检查数据库中是否已经有该条记录
     */
    private boolean hasData(String tempName) {
        Cursor cursor = helper.getReadableDatabase().rawQuery(
                "select id as _id,name from records where name =?", new String[]{tempName});
        //判断是否有下一个
        return cursor.moveToNext();
    }

    /**
     * 清空数据库数据
     */
    private void deleteData() {
        db = helper.getWritableDatabase();
        db.execSQL("delete from records");
        db.close();
    }

   public static class RecordSQLiteOpenHelper extends SQLiteOpenHelper {

        private static String name = "temp.db";
        private static Integer version = 1;

        public RecordSQLiteOpenHelper(Context context) {
            super(context, name, null, version);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            //id自动增长，那么最大200条
            db.execSQL("create table records(id integer primary key autoincrement,name varchar(200))");
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        }


    }
//============================数据库相关(end)====================================


    class MyAdapter extends TagAdapter {

        private List<TagBean> datas;

        public MyAdapter(List<TagBean> datas){

            this.datas = datas;
        }
        @Override
        public int getItemCount() {
            return datas.size();
        }

        @Override
        public View getView(int position, ViewGroup parent) {
            TextView itmeView = (TextView) LayoutInflater.from(SearchActivity.this).inflate(R.layout.tag_item, parent, false);
            final String name = datas.get(position).getName();
            itmeView.setText(name);
            GradientDrawable drawable=new GradientDrawable();
            drawable.setStroke(1,Color.parseColor("#99541D"));
            drawable.setCornerRadius(5);
            drawable.setColor(datas.get(position).getColor());
            itmeView.setBackgroundDrawable(drawable);

            //设置点击事件
            itmeView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //跳转到其他页面
                    action(name);
                }
            });
            return itmeView;
        }
    }


    class TagBean {

        String name;
        int color;

        public TagBean(int color, String name) {

            this.color = color;
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getColor() {
            return color;
        }

        public void setColor(int color) {
            this.color = color;
        }
    }


    private void isTranslucentUtils(int statusColor,boolean isDark) {
        if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 21) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

        } else if (Build.VERSION.SDK_INT >= 21) {
            getWindow().setStatusBarColor(statusColor);
        }

            //小于6.0或者大于4.4
            if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 23) {
                TranslucentUtils.FlymeSetStatusBarLightMode(getWindow(), isDark);
                TranslucentUtils.MIUISetStatusBarLightMode(getWindow(), isDark);
            } else if (Build.VERSION.SDK_INT >= 23) {
                //大于6.0设置字体为黑色。。试用状态栏为白底黑字
                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            }
    }
}
